package br.edu.ufcg.p1.barzin;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import br.edu.ufcg.p1.barzin.event.Assinante;
import br.edu.ufcg.p1.barzin.event.EventBus;
import br.edu.ufcg.p1.barzin.event.PropagandasRecuperadasEvento;
import br.edu.ufcg.p1.barzin.event.TiposDeEventos;
import br.edu.ufcg.p1.barzin.model.Propaganda;

public class PropagandasFragment extends Fragment implements
		Assinante<PropagandasRecuperadasEvento> {

	private List<Propaganda> propagandas;
	private Handler handler = new Handler();
	private boolean jaRecuperou = false;
	
	private int ultimoAtt = 0;
	private int ultimaProp = 0;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.propagandas, container, false);

		return v;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			
		EventBus.getInstance().registraAssinante(
				TiposDeEventos.PROPAGANDAS_RECUPERADAS, this);

	}

	@Override
	public void trataEvento(PropagandasRecuperadasEvento evento) {
		this.propagandas = App.environment().getDao().recuperaPropagandas();
		Log.d("QUANTAS PROPAGANDAS", propagandas.size()+"");
		if (!jaRecuperou) {
			jaRecuperou = true;
			new Timer().schedule(new AtualizaPropTimerTask(), 0, 30000);
		}
	}
	
	private void atualiza(int id) {
		try {
			((ImageView) getView().findViewById(id))
			.setImageBitmap(propagandas.get(ultimaProp).getFoto());
		} catch (Exception e) {

		}
	}
	
	public class AtualizaPropTimerTask extends TimerTask {

		private Runnable runnable = new Runnable() {
			public void run() {
				
				atualiza(R.id.propaganda1);
				ultimaProp++;
				ultimaProp %= propagandas.size();
				
				atualiza(R.id.propaganda2);
				ultimaProp++;
				ultimaProp %= propagandas.size();

				atualiza(R.id.propaganda3);
				ultimaProp++;
				ultimaProp %= propagandas.size();
				
			}
		};

		public void run() {
			handler.post(runnable);
		}
	}
	

}